package com.sctvcloud.dongqu.ui.fragment;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.util.Pair;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.canyinghao.canrefresh.CanRefreshLayout;
import com.google.gson.Gson;
import com.gridsum.tracker.GridsumWebDissector;
import com.jiongbull.jlog.JLog;
import com.ruihang.generalibrary.ui.util.OnItemInternalClick;
import com.ruihang.generalibrary.utils.ListUtils;
import com.sctvcloud.dongqu.R;
import com.sctvcloud.dongqu.application.Constances;
import com.sctvcloud.dongqu.beans.NewsClickCountBean;
import com.sctvcloud.dongqu.beans.NewsIdBean;
import com.sctvcloud.dongqu.beans.NewsItem;
import com.sctvcloud.dongqu.beans.NewsListClickRequestBean;
import com.sctvcloud.dongqu.beans.NewsListClickVo;
import com.sctvcloud.dongqu.http.AbsListNetCallback;
import com.sctvcloud.dongqu.http.AbsNetCallBack;
import com.sctvcloud.dongqu.http.NetUtils;
import com.sctvcloud.dongqu.ui.adapter.CaliNewsListAdapter;
import com.sctvcloud.dongqu.ui.adapter.GreatestAdapter;
import com.sctvcloud.dongqu.ui.util.RBaseItemDecoration;
import com.sctvcloud.dongqu.ui.utils.SkipUtil;
import com.sctvcloud.dongqu.utils.ListTypeUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import okhttp3.MediaType;
import okhttp3.RequestBody;

public class CaligrapherSubFragment extends ColumnBaseFragment implements CanRefreshLayout.OnRefreshListener, CanRefreshLayout.OnLoadMoreListener{
    private final int WHAT_REFRESH_TIME = 919;
    @BindView(R.id.tv_living_refresh)
    protected CanRefreshLayout refreshLayout;
    @BindView(R.id.can_content_view)
    protected RecyclerView calisub_list;
    private CaliNewsListAdapter calisubAdapter;
    private LinearLayoutManager manager;
    private boolean mIsLoading = false;
    private Handler handler;
    private List<NewsItem> fPrograms = new ArrayList<>();
    private List<NewsItem> listAll = new ArrayList<>();
    private NewsItem currentChannel;
    private CalligrapherFragment parentFragment;
    private String channelurl;
    private int newsPageAll = 1;
    private int newsIndex = 0;
    private boolean isRefresh = false;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                if (msg != null) {
                    handMsg(msg);
                }
            }
        };
    }

    public void setParentFragment(CalligrapherFragment parentFragment) {
        this.parentFragment = parentFragment;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_caligraphersub, container, false);
        ButterKnife.bind(this, view);
        return view;
    }



    @Override
    public void onDestroyView() {
        if (handler != null) {
            handler.removeMessages(WHAT_REFRESH_TIME);
        }
        super.onDestroyView();
    }

    @Override
    protected void initViews(View v, @Nullable Bundle savedInstanceState) {
        refreshLayout.setOnRefreshListener(this);
        refreshLayout.setOnLoadMoreListener(this);
        refreshLayout.setLoadMoreEnabled(false);
        manager = new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false);
        calisub_list.setItemAnimator(new DefaultItemAnimator());
        calisub_list.addItemDecoration(new RBaseItemDecoration(2));
        calisub_list.setLayoutManager(manager);
        if(null!= getArguments()) {
            channelurl = getArguments().getString("channelurl", "");
        }
        initData();
    }

    @Override
    protected boolean onFragmentShow(boolean isFirst, boolean isCallFromResume) {
//        if (currentChannel != null && null != parentFragment) {
//            parentFragment.setPlayMedia(currentChannel, false);
//        }
        isCoverStatusColor = true;
  //      initStatusBar();

        return super.onFragmentShow(isFirst, isCallFromResume);
    }

    @Override
    public void onPause() {
        super.onPause();
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    public void onLoadMore() {
        if (newsIndex < newsPageAll - 1) {
            if (!getNewsList(CalligrapherFragment.VIEWTYPE_NEWS, newsIndex + 1)) {
                Toast.makeText(getContext(), "获取更多失败", Toast.LENGTH_LONG).show();
            }
        }
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
    //        if (null != calisubAdapter && calisubAdapter.getItemCount() == 0) {
                onRefresh();
    //        }
        } else {

        }
    }


    @Override
    public void onRefresh() {
        if (mIsLoading) {
            return;
        }
        mIsLoading = true;
//        if (TextUtils.isEmpty(((TvFragment) getParentFragment()).getProgramBackUrl())) {
//            ((TvFragment) getParentFragment()).setLoadingState(true);
//        }

        newsIndex = 0;

        isRefresh = true;
        getNewsList(CalligrapherFragment.VIEWTYPE_NEWS, 0);
    }

    private void handMsg(Message msg) {
        if (msg.what == WHAT_REFRESH_TIME) {
            handler.removeMessages(WHAT_REFRESH_TIME);
        }
    }

    public void setData(final List<NewsItem> fChannels) {
        if (null != fPrograms) {
            this.fPrograms = fChannels;
            if (calisubAdapter != null) {
                calisubAdapter.setData(fPrograms);
                calisubAdapter.notifyDataSetChanged();
            }
        }
    }

    private synchronized void onNetFinish() {
        mIsLoading = false;
        refreshLayout.refreshComplete();
        refreshLayout.loadMoreComplete();
    }

    /**
     * 获取 精选--视讯新闻数据
     *
     * @return
     */
    private boolean getNewsList(final int mode, final int index) {
        if (TextUtils.isEmpty(channelurl)) {
            return false;
        }

        NetUtils.getNetAdapter().getNewsPage(getOwnerName(), channelurl, index, new AbsListNetCallback<NewsItem>(ListTypeUtils.NewsItem()) {
            @Override
            public void onSuc(List<NewsItem> newsItems) {
                newsPageAll = getPageResponse().getData().getPageAll();
                if (ListUtils.isListValued(newsItems)) {
                    newsIndex = index;
                    requestNewsClickCount(newsItems);
//                    if (isRefresh) {
//                        list.clear();
//                        list.addAll(newsItems);
//                        isRefresh = false;
//                    } else {
//                        list.addAll(newsItems);
//                    }
//                    setData(list);
                }
            }

            @Override
            public void onEnd() {
                super.onEnd();
//                if (newsIndex >= newsPageAll - 1) {
//                    refreshLayout.setLoadMoreEnabled(false);
//                } else {
//                    refreshLayout.setLoadMoreEnabled(true);
//                }
//                onNetFinish();//暂时使用calledIndex来保存mode
            }


            @Override
            public void onError(Throwable ex, String errorMsg, int netCode) {
                super.onError(ex, errorMsg, netCode);
            }
        });
        return true;
    }
    private List<NewsItem> newsItems;
    /**
     * 获取新闻列表点击量
     *
     * @param list
     */
    private void requestNewsClickCount(final List<NewsItem> list) {
        if (ListUtils.isListValued(list)) {
            newsItems = new ArrayList<>();
            newsItems.addAll(list);
            List<NewsIdBean> newsIdList = new ArrayList<>();
            NewsIdBean newsBean;
            for (int i = 0; i < list.size(); i++) {
                String type = "10";//默认不返回点击量
                if (list.get(i) instanceof NewsItem) {
                    NewsItem item = (NewsItem) list.get(i);
                    newsBean = new NewsIdBean();
                    newsBean.setId(item.getNewsId());
                    switch (item.getNewsType()) {
                        case Constances.NEWS_TYPE_GRAPHIC:
                        case Constances.NEWS_TYPE_AUDIO:
                        case Constances.NEWS_TYPE_VIDEO:
                        case Constances.NEWS_TYPE_H5:
                            //新闻详情
                            type = "0";
                            break;
                        case Constances.NEWS_TYPE_LIVE:
                            //直播详情
                            type = "1";
                            break;
                        default:
                            //其他详情
                            newsBean.setId(item.getNewsId());
                            type = "10";
                            break;
                    }
                    newsBean.setType(type);
                    newsIdList.add(newsBean);
                } else {
                    newsBean = new NewsIdBean();
                    newsBean.setId("1");
                    newsBean.setType(type);
                    newsIdList.add(newsBean);
                }
            }
            if (ListUtils.isListValued(newsIdList)) {
                NewsListClickRequestBean requestBean = new NewsListClickRequestBean();
                requestBean.setNewsIds(newsIdList);
                Gson gson = new Gson();
                String newsId = gson.toJson(requestBean);
                RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), newsId);
                NetUtils.getNetAdapter().getViewsList(getOwnerName(), body, new AbsNetCallBack<NewsListClickVo>(NewsListClickVo.class) {
                    @Override
                    public void onSuc(NewsListClickVo newsListClickVo) {
                        if (null != newsListClickVo && ListUtils.isListValued(newsListClickVo.getResult())) {
                            List<NewsClickCountBean> countList = newsListClickVo.getResult();
                            for (int i = 0; i < countList.size(); i++) {
                                if (newsItems.get(i) instanceof NewsItem) {
                                    NewsItem item = (NewsItem) newsItems.get(i);
                                    if (item.getNewsType() == Constances.NEWS_TYPE_H5) {
                                        if (!TextUtils.isEmpty(item.getNewsId()) && countList.get(i).getId().equalsIgnoreCase(item.getNewsId())) {
                                            ((NewsItem) newsItems.get(i)).setReadCount(countList.get(i).getViews());
                                        }
                                    } else {
                                        if (!TextUtils.isEmpty(item.getUrlNewsId()) && countList.get(i).getId().equalsIgnoreCase(item.getUrlNewsId())) {
                                            ((NewsItem) newsItems.get(i)).setReadCount(countList.get(i).getViews());
                                        }
                                    }
                                }
                            }
                        }


                        if (isRefresh) {
                            listAll.clear();
                            listAll.addAll(newsItems);
                            isRefresh = false;
                        } else {
                            listAll.addAll(newsItems);
                        }
                        setData(listAll);
                        if (newsIndex >= newsPageAll - 1) {
                            refreshLayout.setLoadMoreEnabled(false);
                        } else {
                            refreshLayout.setLoadMoreEnabled(true);
                        }


                    }

                    @Override
                    public void onEnd() {
                        super.onEnd();

                        onNetFinish();//暂时使用calledIndex来保存mode
                    }

                    @Override
                    public void onError(Throwable ex, String errorMsg) {
                        super.onError(ex, errorMsg);
                    }
                });
            }
        }
    }

    private void initData() {


        if (calisubAdapter == null) {
            calisubAdapter = new CaliNewsListAdapter(getContext(), fPrograms, 0).setItemInternalClick(livingOnItemClick);
            calisub_list.setAdapter(calisubAdapter);
        } else {
            calisubAdapter.addDatas(fPrograms);
            calisubAdapter.notifyDataSetChanged();
        }
        onRefresh();
    }

    int oldPos = -1;
    private OnItemInternalClick livingOnItemClick = new OnItemInternalClick() {
        @Override
        public void onItemInternalClick(View itemView, View view, int position) {
            NewsItem fProgram = calisubAdapter.getItem(position);
            if (null != fProgram) {
   //             currentChannel = fProgram;
   //             if (null != parentFragment) {
   //                 parentFragment.setPlayMedia(fProgram, false);
   //             }

   //             initStatusBar();

                calisubAdapter.setSelectPos(position);
                calisubAdapter.notifyDataSetChanged();
                ArrayList<Pair<String, String>> pairs = new ArrayList<>();
                pairs.add(new Pair<>("页面", "首页"));
                pairs.add(new Pair<>("栏目", tag));
                pairs.add(new Pair<>("行为类型", "点击"));
                GridsumWebDissector.getInstance().trackEvent(CaligrapherSubFragment.this, "", ((NewsItem) calisubAdapter.getItem(position)).getNewsTitle(), "", 200, pairs);

                HashMap<String, String> map = new HashMap<>();
                for (Pair<String, String> p : pairs) {
                    map.put(p.first, p.second);
                }
                SkipUtil.skipWithNewsItem(getActivity(), (NewsItem) calisubAdapter.getItem(position), map);
            }
        }
    };

    public void setChannelurl(String channelurl) {
        this.channelurl = channelurl;
    }

    public String getChannelurl() {
        return this.channelurl;
    }
}
